package com.yqyd.web.controller.hy.app;

import cn.hutool.json.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.yqyd.common.annotation.Anonymous;
import com.yqyd.common.constant.UserConstants;
import com.yqyd.common.core.domain.R;
import com.yqyd.common.core.domain.entity.SysUser;
import com.yqyd.common.core.redis.RedisCache;
import com.yqyd.common.utils.SecurityUtils;
import com.yqyd.common.utils.WechatUtils;
import com.yqyd.framework.web.service.SysLoginService;
import com.yqyd.hy.domain.HyCategory;
import com.yqyd.hy.domain.HyGoods;
import com.yqyd.hy.dto.GoodsSearchDto;
import com.yqyd.hy.dto.SignDto;
import com.yqyd.hy.service.IHyCategoryService;
import com.yqyd.hy.service.IHyGoodsService;
import com.yqyd.hy.vo.UserInfoVo;
import com.yqyd.system.service.ISysConfigService;
import com.yqyd.system.service.ISysUserService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

/**
 * 分类
 */
@RestController
@RequestMapping("/api/app/login")
@CrossOrigin
public class ApiLoginController {

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private SysLoginService loginService;

    private final static String APPID = "wx70204e73d64c27cd";
    private final static String APP_SECRET = "0730dca831e2f9d9b4562ea46fe3d174";
    private final static String PWD = "123456";


    @Resource
    private RedisCache redisCache;


    @SneakyThrows
    @PostMapping("/AuthPhone/{code}")
    @Anonymous
    public R authPhone(@PathVariable String code) {
        String token = redisCache.getCacheObject("wechat_token");
        if(StringUtils.isEmpty(token)){
            return R.fail("微信授权失败：token为空");
        }
        JSONObject json = WechatUtils.phonenumber(code, token);
        Integer resCode = json.getInt("errcode");
        String resMsg = json.getStr("errmsg");
        if (resCode != 0) {
            return R.fail("手机号授权失败：" + resMsg);
        }
        String phone = json.getJSONObject("phone_info").getStr("phoneNumber");
        if (StringUtils.isEmpty(phone)) {
            return R.fail("手机号获取失败");
        }
        return R.ok(ImmutableMap.of("phone", phone));
    }

    @Anonymous
    @PostMapping("/sign")
    public R<ImmutableMap<String, Object>> sign(@RequestBody @Validated SignDto dto) {
        String openId = WechatUtils.Openid(dto.getCode(), APPID,APP_SECRET);
        if (StringUtils.isEmpty(openId)) {
            return R.fail("微信上授权登录失败：OPENID为空");
        }
        // TODO: 注册用户
        SysUser sysUser = new SysUser();
        sysUser.setUserName(openId);
        sysUser.setNickName(dto.getSurname() + dto.getName());
        sysUser.setPhonenumber(dto.getPhone());
        sysUser.setSex(dto.getSex());
        sysUser.setPassword(SecurityUtils.encryptPassword(PWD));
        int row = sysUserService.insertUser(sysUser);
        if (row > 0) {
            // TODO: 登录
            return R.ok(ImmutableMap.of("token", loginService.login(openId, PWD, "", "")));
        }
        return R.fail("注册失败");
    }

    @Anonymous
    @GetMapping("/login")
    public R<ImmutableMap<String, Object>> login(@RequestParam("code") String code) {
        String openId = WechatUtils.Openid(code,APPID, APP_SECRET);
        if (StringUtils.isEmpty(openId)) {
            return R.fail("微信上授权登录失败：OPENID为空");
        }
        // TODO: 注册用户
        SysUser user = sysUserService.selectEasyUserByOpenId(openId);
        if (user == null) {
            return R.ok(ImmutableMap.of("signed", false));
        }
        // TODO: 登录
        return R.ok(ImmutableMap.of("signed", true, "token", loginService.login(openId, PWD, "", ""),
                "user", new UserInfoVo()
                        .setUserId(user.getUserId())
                        .setSurname(user.getNickName().substring(0, 1))
                        .setName(user.getNickName().substring(1))
                        .setPhone(user.getPhonenumber())
                        .setSex(user.getSex())
        ));
    }


    @GetMapping("/userInfo")
    public R<UserInfoVo> userInfo() {
        SysUser user = sysUserService.selectUserById(SecurityUtils.getUserId());
        if (user == null) {
            return R.fail("用户不存在");
        }
        return R.ok(new UserInfoVo()
                .setUserId(user.getUserId())
                .setSurname(user.getNickName().substring(0, 1))
                .setName(user.getNickName().substring(1))
                .setPhone(user.getPhonenumber())
                .setSex(user.getSex())
        );
    }


}
